var memory;
var imported = {
    memory: new WebAssembly.Memory({ initial: 1000 }),// 增加初始内存大小
    abort: function (a, b, c, d) { console.log("abort"); },
    sin: Math.sin,
    "performance.now": () => performance.now()  // 提供 performance.now 的替代实现
};

imported["console.log"] = function (a) {
    console.log(new Uint8Array(memory.buffer, a, 1));
}
 
function test(file, func, ...args) {
    const bytes = readbuffer(file);
    const mod = new WebAssembly.Module(bytes);
    const instance = new WebAssembly.Instance(mod, { env: imported });
    memory = instance.exports.memory;
 
    // 定义学生信息对象
    const studentInfo = {
        id: 1,
        name: "Bob",
        age: 22,
        grade: 4,
        time: 0.0, // 初始时间为0
        vars: new Array(1000).fill(1) // 初始化 1000 个 u32 类型的字段
    };

    // 将学生信息对象写入 WebAssembly 内存
    function writeStudentInfoToMemory(studentInfo, memory) {
        const studentSize = 24 + studentInfo.name.length + 1 + 1000 * 4; // 24字节固定部分 + 名字长度 + 终止符 + 1000个u32字段
        const studentBuffer = new Uint8Array(memory.buffer, 0, studentSize); // 从内存起始位置开始分配
        const studentPtr = studentBuffer.byteOffset;

        // 写入学生信息
        const view32 = new Uint32Array(memory.buffer, studentPtr, 3);
        view32[0] = studentInfo.id;
        view32[1] = studentInfo.age;
        view32[2] = studentInfo.grade;

        const view64 = new Float64Array(memory.buffer, studentPtr + 16, 1); // 16 是 8 的倍数
        view64[0] = studentInfo.time;

        const view8 = new Uint8Array(memory.buffer, studentPtr + 24, studentInfo.name.length + 1);
        for (let i = 0; i < studentInfo.name.length; i++) {
            view8[i] = studentInfo.name.charCodeAt(i);
        }
        view8[studentInfo.name.length] = 0; // 终止符

        const varsPtr = studentPtr + 24 + studentInfo.name.length + 1; // 名字后面的 1 字节终止符
        const varsView = new Uint32Array(memory.buffer, varsPtr, 1000);
        for (let i = 0; i < 1000; i++) {
            varsView[i] = studentInfo.vars[i];
        }

        return studentPtr;
    }

    const inputStudentPtr = writeStudentInfoToMemory(studentInfo, memory);

    console.log(`Input student pointer: ${inputStudentPtr}`);
    console.log(`Memory buffer before calling withInputAndOutput:`, new Uint8Array(memory.buffer, 0, 64));

   
    const outputStudentPtr = instance.exports[func](inputStudentPtr, ...args);

    
    const startTime = performance.now();
    // 从内存中读取返回的学生信息
    const outputStudent = readStudentInfoFromMemory(outputStudentPtr, memory);
    const endTime = performance.now();
    console.log(`Output student: ID=${outputStudent.id}, Name=${outputStudent.name}, Age=${outputStudent.age}, Grade=${outputStudent.grade}, Time=${outputStudent.time.toFixed(6)} ms`);
    console.log(`calculate time: ${(endTime - startTime)} ms`);
    // 打印前几个 vars 字段
    console.log(`First few vars: ${outputStudent.vars.slice(0, 5).join(", ")}`);

    //console.log(`Memory buffer after calling withInputAndOutput:`, new Uint8Array(memory.buffer, 0, 64));
}

// 从 WebAssembly 内存中读取学生信息
function readStudentInfoFromMemory(ptr, memory) {
    const view32 = new Uint32Array(memory.buffer, ptr, 3);
    const id = view32[0];
    const age = view32[1];
    const grade = view32[2];
    const view64 = new Float64Array(memory.buffer, ptr + 16, 1); // 16 是 8 的倍数
    const time = view64[0];

    const namePtr = ptr + 24;
    const view8 = new Uint8Array(memory.buffer, namePtr);
    let name = "";
    let i = 0;
    while (true) {
        const charCode = view8[i];
        if (charCode === 0) break;
        name += String.fromCharCode(charCode);
        i++;
    }

    const varsPtr = ptr + 24 + i + 1; // 名字后面的 1 字节终止符
    const varsView = new Uint32Array(memory.buffer, varsPtr, 1000);
    const vars = Array.from(varsView);

    return { id, name, age, grade, time, vars };
}

filepath = "build/test_object1000.wasm";
test(filepath , "withInputAndOutput");